import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CommonService } from 'src/app/services-common/common.service';
import { defalutImg } from 'src/app/comm';
import { ProjectManageService } from '../project-manage.service';

@Component({
  selector: 'app-project-list',
  templateUrl: './project-list.component.html',
  styleUrls: ['./project-list.component.scss'],
  providers: [DatePipe]
})
export class ProjectListComponent implements OnInit {

  fallback: string = defalutImg;
  isCollapse: boolean = true;
  searchParams: any = {
    id: '', // 编号
    projectName: '', // 项目名称
    platform: '', // 平台 1: ios 2: 安卓 3: Windows
    uId: '', // 应用唯一标识
    subtitle: '',
    group: '', // 分组
    lastVersion: '', // 最新版本名称
    lastVersionid: '', // 最新版本号
    startTime: '', // 更新开始时间
    endTime: '', // 更新结束时间
    updateFlag: '', // 是否强制更新 0: 否 1: 是
  };
  updateDates: any = [];

  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: Array<any> = [];

  // 新增 | 编辑 Modal
  isModifyVisible: boolean = false;
  modalType: number = 0;
  updateItems: any = {};

  validateForm!: FormGroup;
  uploadLoading: boolean = false;

  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private commonService: CommonService,
    private datePipe: DatePipe,
    private services: ProjectManageService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      projectName: ['', [Validators.required]],
      platform: ['1'], // 平台 1: ios 2: 安卓 3: Windows
      uId: ['', [Validators.required]],
      subtitle: ['', [Validators.required]],
      edition: ['0'], // 0不区分 1为开发版，2为生产版，3为预生产版 4为预览版
      logo: [''],
      group: ['', [Validators.required]]
    });

    this.loadTable();
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.tableLoading = true;
    const res: any = await this.services.queryProjectListData(params);
    this.tableParams.tableLoading = false;
    
    if (res.code == 0) {
      const { records, total } = res.data || {};
      this.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  platformSearchChange(value: any) {
    this.searchParams.uId = '';
    this.searchParams.subtitle = '';
  }

  searchData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    for (let key in this.searchParams) {
      this.searchParams[key] = '';
    }
    this.updateDates = [];
    this.tableParams.page = 1;
    this.loadTable();
  }

  dateChange(result: any) {
    this.searchParams.startTime = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    this.searchParams.endTime = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
  }

  async deleteItem(item: any) {
    const res: any = await this.services.deleteProjectItem({id: item.id});
    if (res.code == 0) {
      this.message.success('删除成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 新增 | 编辑 项目
   * @param type 
   * @param item 
   * ----------------------------------------------------------------
   */
  showModal(type: number, item?: any) {
    this.modalType = type;
    this.validateForm.reset();

    if (item) {
      this.updateItems = item;
      this.validateForm.patchValue({
        projectName: item.projectName || '',
        platform: String(item.platform) || '', // 平台 1: ios 2: 安卓 3: Windows
        uId: item.uid || '',
        subtitle: item.subtitle || '',
        edition: String(item.edition) || '', // 0不区分 1为开发版，2为生产版，3为预生产版 4为预览版
        logo: item.logo || '',
        group: item.group || ''
      })
    } else {
      this.validateForm.get('platform')?.setValue('1');
      this.validateForm.get('edition')?.setValue('0');
    }

    this.platformChange(this.validateForm.value.platform);
    Object.values(this.validateForm.controls).forEach(control => {
      if (control.invalid) {
        control.markAsPristine();
        control.updateValueAndValidity({ onlySelf: true });
      }
    });
    this.isModifyVisible = true;
  }

  handleCancel() {
    this.isModifyVisible = false;
  }

  platformChange(type: any) {
    // 平台为ios 时应用标识和SUBTITLE必填
    if (type == 1) {
      ['uId', 'subtitle'].forEach((item: any) => {
        this.validateForm.get(item)!.setValidators(Validators.required);
        this.validateForm.get(item)!.markAsDirty();
      })
    } else {
      ['uId', 'subtitle'].forEach((item: any) => {
        this.validateForm.get(item)?.setValue('');
        this.validateForm.get(item)!.clearValidators();
        this.validateForm.get(item)!.markAsPristine();
      })
    }

    ['uId', 'subtitle'].forEach((item: any) => {
      this.validateForm.get(item)!.updateValueAndValidity();
    })
  }

  async submitForm() {
    if (this.validateForm.valid) {
      let params = {
        project: {
          ...this.validateForm.value
        }
      }
      
      let res: any
      if (this.modalType == 0) {
        res = await this.services.saveProjectItem(params);
      } else {
        params.project.id = this.updateItems.id;
        res = await this.services.updateProjectItem(params);
      }

      if (res.code == 0) {
        this.isModifyVisible = false;
        this.message.success('操作成功');
        this.loadTable();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  // Logo
  onModalPreview(ev: any) {
    const { originFileObj }: any = ev?.file;
    this.uploadInterface(originFileObj);
  }
  
  async uploadInterface(file: any) {
    if (!file || this.uploadLoading) {
      return
    }

    try {
      this.uploadLoading = true;
      const res: any = await this.commonService.uploadFileData(file, 'project-manage');
      this.uploadLoading = false;

      if (res.code == 0) {
        this.message.success('图片上传成功');
        this.validateForm.get('logo')?.setValue(res.data);
      } else {
        this.message.error(res.message || '图片上传失败');
      }
    } catch (error: any) {
      this.uploadLoading = false;
      this.validateForm.get('logo')?.setValue('');
      this.message.error(error || '图片上传失败');
    }
  }

  deleteImg() {
    this.validateForm.get('logo')?.setValue('');
  }

  // 计算包大小
  calculationPackage(sizeNum: number) {
    return sizeNum && !isNaN((sizeNum / 1024 / 1024)) ? (sizeNum / 1024 / 1024).toFixed(2) + 'MB' : '-';
  }

  // Change PageIndex
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // Change PageSize
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }
}
